import { ScrollView, View, Text } from '@tarojs/components'
import { useState } from 'react'

import NoExploit from '@/components/NoExploit'
import tools from '@/common/tools'
import { getOrderListReq } from '@/common/api'
import { ERR_MES } from '@/common/constant'
import { useDidShow } from '@tarojs/taro'
import { useUpdateEffect } from '@/common/hooks'

const OrderList = ({ userPhone }) => {
  const [orderList, setOrderList] = useState<OrderProps[]>([])
  const [isRefresh, setIsRefresh] = useState<boolean>(false) // 是否处于下拉刷新状态

  useDidShow(() => {
    getData()
  })

  useUpdateEffect(() => {
    isRefresh && getData()
  }, [isRefresh])

  const getData = async () => {
    tools.showLoading()
    const response = await getOrderListReq({
      userPhone
    })
    tools.hideLoading()
    setIsRefresh(false)

    const { result } = response
    if (response.code === 200) {
      setOrderList(result || [])
    } else {
      tools.showToast(result || ERR_MES)
    }
  }

  const handlePullDownRefresh = () => {
    setIsRefresh(true)
  }

  if (orderList.length === 0) {
    return <NoExploit content='暂无数据' />
  }

  return (
    <ScrollView
      scrollY
      style={{ height: '100%' }}
      className='order-list-box'
      refresherEnabled
      refresherTriggered={isRefresh}
      onRefresherRefresh={handlePullDownRefresh}
    >
      {orderList.map((item) => {
        const { departureCityName, destinationCityName, arrTimeStr, dptTimeStr, price } = item
        return (
          <View key={item.id} className='item'>
            <View className='left'>
              <View className='line'>
                <Text className='city-name'>{departureCityName}</Text> -
                <Text className='city-name'>{destinationCityName}</Text>
                <View className='time'>{`${dptTimeStr} - ${arrTimeStr}`}</View>
              </View>
            </View>
            <View className='right'>¥ {price}</View>
          </View>
        )
      })}
    </ScrollView>
  )
}

export default OrderList
